//
//  HMThumbnailView.swift
//  weibo10
//
//  Created by mac on 15/10/22.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SDWebImage

/// 图片之间的间距
let statusViewItemPicMargin: CGFloat = 8
// 缩略图可重用ID
let statusViewCellID = "statusViewCellID"
/// 缩略图视图
class HMThumbnailView: UICollectionView {
    var viewModel: HMStatusViewModel? {
        didSet{
            sizeToFit()
            reloadData()
        }
    }
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calItemSize()
    }
    init(){
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = statusViewItemPicMargin
        
        layout.minimumLineSpacing = statusViewItemPicMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        dataSource = self
        // 注册可重用cell
        registerClass(HMThumbnailViewCell.self, forCellWithReuseIdentifier: statusViewCellID)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
// MARK: - 数据源方法
extension HMThumbnailView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel?.thumbnailUrls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCellWithReuseIdentifier(statusViewCellID, forIndexPath: indexPath) as! HMThumbnailViewCell
        
        cell.imageUrl = viewModel!.thumbnailUrls![indexPath.item]
        
        return cell
    }
}
// MARK: - 计算视图大小
extension HMThumbnailView {
    /// 计算item的大小
    private func calItemSize() -> CGSize {
        // 1. 准备工作
        let rowCount:CGFloat = 3
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * statusCellMargin
        let width = (maxWidth - (rowCount - 1) * statusViewItemPicMargin) / rowCount
        // 2.
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: width, height: width)
        // 3.获取图片数量
        
        let count = viewModel?.thumbnailUrls?.count ?? 0
        if count == 0 {
            return CGSizeZero
        }
        if count == 1 {
            var size = CGSize(width: 150, height: 120)
            if let key = viewModel?.thumbnailUrls?.first?.absoluteString {
                // 查询缓存的图片，key - url的完整字符串
                let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
                size = image.size
            }
            size.width = size.width < 40 ? 40 : size.width
            if size.width > 300 {
                let width: CGFloat = 300
                let height = size.height * width / size.width
                size = CGSize(width: width, height: height)
            }
            layout.itemSize = size
            return size
        }
        if count == 4 {
            let w = 2 * width + statusViewItemPicMargin
            return CGSize(width: w, height: w)
        }
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let w = rowCount * width + (rowCount - 1) * statusViewItemPicMargin
        let h = row * width + (row - 1) * statusViewItemPicMargin
        return CGSize(width: w , height: h)
        
    }
}
class HMThumbnailViewCell: UICollectionViewCell {
    var imageUrl: NSURL?{
        didSet{
            iconView.sd_setImageWithURL(imageUrl, placeholderImage: nil, options: [SDWebImageOptions.RetryFailed,SDWebImageOptions.RefreshCached])
        }
    }
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 懒加载控件
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        // 填充模式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        // 必须裁剪
        iv.clipsToBounds = true
        
        return iv
    }()
    private func setupUI(){
        // 添加控件
        contentView.addSubview(iconView)
        // 布局: 需要注意，必须自动布局，因为cell变化，大小可能不一样
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
}
